﻿using AutoMapper;
using IMES.Common.Domain.DurianModel;
using IMES.Common.Domain.SirModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace GlennQuigmire.API.Application.Commands
{
    public class DefectiveCreateHander : IRequestHandler<DefectiveCreateCommand, Result>
    {

        private readonly IMapper mapper;
        private readonly IBaseRepositorys<Defectives> baseRepositorys;
        private readonly IBaseRepositorys<SystemLogs> systemLogsRepositorys;
        private readonly ILogger<DefectiveCreateHander> logger;

        public DefectiveCreateHander(IMapper mapper, IBaseRepositorys<Defectives> baseRepositorys, ILogger<DefectiveCreateHander> logger, IBaseRepositorys<SystemLogs> systemLogsRepositorys)
        {
            this.mapper = mapper;
            this.baseRepositorys = baseRepositorys;
            this.logger = logger;
            this.systemLogsRepositorys = systemLogsRepositorys;
        }

        /// <summary>
        /// 添加不良品项
        /// </summary>
        /// <param name="request">添加不良品项请求对象</param>
        /// <param name="cancellationToken">允许异步</param>
        /// <returns>添加不良品项响应对象</returns>
        public async Task<Result> Handle(DefectiveCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result =new Result();
                Defectives defectives = mapper.Map<Defectives>(request);
                defectives.CreateDate = DateTime.Now;
                defectives.CreateName = request.CreateName;
                if(string.IsNullOrEmpty( defectives.DefectiveNo ))
                {
                    defectives.DefectiveNo = Guid.NewGuid().ToString().Replace("-", "");
                }
                result.Code =  baseRepositorys.Add(defectives);
                if (result.Code > 0)
                {
                    SystemLogs systemLogs = new SystemLogs();
                    systemLogs.LogeName = defectives.CreateName+"新增了不良品项";
                    systemLogs.LogeTime = DateTime.Now;
                    systemLogsRepositorys.Add(systemLogs);
                    result.Messege = "添加成功";
                }
                else
                {
                    result.Messege = "添加失败";
                }
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "不良品项添加方法调用出错");  
                throw;
            }
        }
    }
}
